package core.proto.rightwindow;

import static app.constants.CollabVizConstants.*;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import javax.swing.Timer;

import org.apache.commons.io.FilenameUtils;

import core.proto.InfoViz;
import core.proto.annotation.Annotation;
import core.proto.rightwindow.BoardPane.postItPair;

public class PostItStorer {
	public PostItStorer(){
		ActionListener taskPerformer = new ActionListener() {
		      public void actionPerformed(ActionEvent evt) {
		    	  runStorageProcessing();
		      }
		  };
		  
		int delay = 10000;
		 Timer t = new Timer(delay, taskPerformer);
		 t.setRepeats(true);
		 t.start();
	}
	
	private void runStorageProcessing() {
		PrintWriter writer = null;
		PrintWriter writerWeight = null;
		try {
			File f = new File(FilenameUtils.concat(NOTEPAD_HIGHLIGHT_FOLDER, POSTITS_FILE_NAME));
			if (f.exists()){
				f.delete(); // clean start. 
			}
			
			writer = new PrintWriter(new FileWriter(f));

			for(PostIt p : BoardPane.getAllPostIts()){
				if(p.getOwner().equals(InfoViz.UserID)){
					String text = p.getText();
					text = text.replaceAll(ANNOTATION_DELIMITER, "");
					text = text.replaceAll("\\n", "<NEWLINE>");
					text = text.replaceAll("\n", "<NEWLINE>");
					text = text.replaceAll(System.getProperty("line.separator"),
							" ");
					text = text.replaceAll("\\r|\\n", "<NEWLINE>");
					String x = p.getX() + "";
					String y = p.getY() + "";
					String sid = p.getSessionId() + "";
					
					String linksIn = BoardPane.getInstance().getSingleLinksStringIn(p);
					String linksOut = BoardPane.getInstance().getSingleLinksStringOut(p);
	
					
					String out = text + ANNOTATION_DELIMITER +
							x + ANNOTATION_DELIMITER + y + ANNOTATION_DELIMITER + sid
							+ ANNOTATION_DELIMITER + p.getGroup() + ANNOTATION_DELIMITER 
							+ p.getArea().getBackground().getRGB();
					writer.println(out);
				}
			}
			
			 File f2 = new File(FilenameUtils.concat(NOTEPAD_HIGHLIGHT_FOLDER, POSTITS_LINKS_FILE));
			  if (f2.exists()){
				  f2.delete(); // clean start. 
				}
			  writerWeight = new PrintWriter(new FileWriter(f2));
				
				for(postItPair pip : BoardPane.singleLinkMap){
					writerWeight.println(pip.a.getSessionId() + "|" + pip.b.getSessionId() 
							+ "=" + BoardPane.singleSizeMap.get(pip));
				}
				
				
		} catch (IOException e) {
			System.err.println(e.getStackTrace());
		} finally {
			if (writer != null){
		//		writer.flush();
				writer.close();
				
			}
			if(writerWeight != null){
			//	writerWeight.flush();
				writerWeight.close();
			}
		}
		
		
	}

	public static ArrayList<PostIt> getStoredPostits() {
		ArrayList<PostIt> listOut = new ArrayList<PostIt>();
		
		try{
			
			FileInputStream fstream = new FileInputStream(FilenameUtils.concat(NOTEPAD_HIGHLIGHT_FOLDER, POSTITS_FILE_NAME));

			  DataInputStream in = new DataInputStream(fstream);
			  BufferedReader br = new BufferedReader(new InputStreamReader(in));
			  String strLine;
			  ArrayList<String> postsFromFile = new ArrayList<String>();
			  
			  while ((strLine = br.readLine()) != null)   {
				  // Print the content on the console
				  
				  if(!strLine.isEmpty()){
					 String[] elements = strLine.split(ANNOTATION_DELIMITER);
					  
					  PostIt p = new PostIt(InfoViz.UserID, false);
					  
					  String textIn = elements[0];
					 textIn = textIn.replaceAll("<NEWLINE>", System.getProperty("line.separator"));
					  p.setText(textIn);
					  
					  p.setLocation(Integer.parseInt(elements[1]), Integer.parseInt(elements[2]));
					  
					  p.setSessionID(Long.parseLong(elements[3]));
					  
					  p.setGroup(elements[4]);
					  
					  Color c = new Color(Integer.parseInt(elements[5]));
					  
					  p.getArea().setBackground(c);
					  

					  listOut.add(p);
				  }
				 
			  }
			  


			  in.close();
			  
			  
			  return listOut;
		  }catch (Exception e){//Catch exception if any
			   System.err.println("Error: " + e.getMessage());
		  }
		
		return listOut;
	}
	
	public void handleStoredLinks(){
		try{
			
			FileInputStream fstream = new FileInputStream(FilenameUtils.concat(NOTEPAD_HIGHLIGHT_FOLDER, POSTITS_LINKS_FILE));

			  DataInputStream in = new DataInputStream(fstream);
			  BufferedReader br = new BufferedReader(new InputStreamReader(in));
			  String strLine;
			  
			  while ((strLine = br.readLine()) != null)   {
				  // Print the content on the console
				  
				  if(!strLine.isEmpty()){
					  PostIt left = null;
					  PostIt right = null;
					  
					  long leftID = Long.parseLong(strLine.substring(0, strLine.indexOf("|")));
					  long rightID = Long.parseLong(strLine.substring(strLine.indexOf("|") + 1, strLine.indexOf("=")));
					  float weight = Float.parseFloat(strLine.substring(strLine.indexOf("=") + 1, strLine.length()));
					  
					  for(PostIt p :BoardPane.getAllPostIts()){
						  if(p.getSessionId() == leftID)
							  left = p;
						  
						  if(p.getSessionId() == rightID)
							  right = p;
					  }
					  
					  if(left != null && right != null){
						  BoardPane.singleLink(left, null);
						  BoardPane.singleLink(right, null);
						  
						  for(postItPair pip : BoardPane.singleLinkMap){
							  if(pip.a == left && pip.b == right){
								  BoardPane.singleSizeMap.put(pip, weight);
							  }
						  }
					  }
					  
				  }
			  }
		}catch (Exception e){//Catch exception if any
			   System.err.println("Error: " + e.getMessage());
		 }
	}
	
	
}
